package com.xinjiang.electricpower.timer;

import lombok.extern.slf4j.Slf4j;
import org.pentaho.di.core.KettleEnvironment;
import org.pentaho.di.trans.Trans;
import org.pentaho.di.trans.TransMeta;

import java.io.InputStream;
import java.util.Map;

/**
 * @author zhanghui
 * @date 2023/2/14 10:34
 * @Description kettle执行ktr脚本工具
 */
@Slf4j
public class KettleQuartz {

    public static final String CJ_BH = "采集闭环";

    public static final String YIN_XIAO = "营销业务";

    public static final String GD_FW = "供电服务";

    /**
     * 执行转换
     * @param initKettleParam 参数
     * @return
     */
    public static boolean runKettleTransfer(Map<String, String> initKettleParam, String orderType, InputStream in) {
        Trans trans = null;
        try {
            // 初始化
            KettleEnvironment.init();
            //EnvUtil.environmentInit();
            //流的方式运行ktr 文件
            TransMeta transMeta = new TransMeta(in, null, true, null, null);
//            String fname = "D:\\XJCSE\\kettle.ktr";
//            TransMeta transMeta = new TransMeta(fname);
            // 转换
            trans = new Trans(transMeta);
            // 初始化trans参数，脚本中获取参数值：${variableName}
            if (initKettleParam != null) {
                for (String variableName : initKettleParam.keySet()) {
                    trans.setVariable(variableName, initKettleParam.get(variableName));
                }
            }
            // 执行转换
            trans.execute(null);
            // 等待转换执行结束
            trans.waitUntilFinished();
            if (trans.getErrors() > 0) {
                log.error("ExecKettleUtil@runKettleTransfer:" + orderType + " 执行失败");
            } else {
                log.info("ExecKettleUtil@runKettleTransfer:" + orderType + " 执行成功");
            }
            return true;
        } catch (Exception e) {
            log.error("ExecKettleUtil@runKettleTransfer:{} {}" + orderType, e);
            return false;
        }
    }
}
